import { ref } from 'vue'
import { defineStore } from 'pinia'
import { loginAPI } from '@/apis/user';
import { useCartStore } from './cartStore';

export const useUserStore = defineStore('user', () => {
  const cartStore = useCartStore()
  const userInfo = ref({})

  // 登录
  const getUserInfo = async ({account, password}) => {
    const res = await loginAPI({account, password})
    userInfo.value = res.result
    // 合并购物车
    await cartStore.mergeCart()
    // 查询最新购物车
    cartStore.updateNewList()
  }

  const clearUserInfo = () => {
    userInfo.value = {}
    // 退出时删除购物车
    cartStore.clearCart()
  }

  return { userInfo, getUserInfo, clearUserInfo }
}, {    
    persist: true  
})